package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.dto.PageResult;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> brandPageQuery(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //设置分页信息
        PageHelper.startPage(page, rows);
        //封装查询条件
        Example example = new Example(Brand.class);
        //判断key是否有值
        if(StringUtils.isNotBlank(key)){
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name", "%"+key+"%");
            criteria.orEqualTo("letter", key.toUpperCase());
        }
        //判断是否有排序字段  select * from xxx order by xxx desc
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }
        //数据库查询【分页查询】
        List<Brand> brands = brandMapper.selectByExample(example);
        //判空
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //得到PageHelper的分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        //将PageHelper的分页对象转成自定义的分页对象
        PageResult<Brand> pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
        return pageResult;
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        try {
            //保存品牌数据
            brandMapper.insertSelective(brand);
            //保存中间表
            brandMapper.insertCategoryAndBrand(cids, brand.getId());
        }catch (Exception e){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public Brand findBrandById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if(brand==null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    public List<Brand> findBrandsByCategoryId(Long id) {
        List<Brand> list = brandMapper.findBrandsByCategoryId(id);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return list;
    }

}
